import sys

print("\n****************")
print('dev hhinfo server.')
print("****************\n")


from fastapi import FastAPI ,WebSocket , Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
import json
import uvicorn
from decimal import Decimal
from apilib.component import TCompManager, compManager

import apilib.common.compFile
import apilib.common.compDB
import apilib.common.compRedis
import apilib.common.compObj
import apilib.common.compWs
import apilib.common.compBucket
import apilib.common.compPump


import apilib.plugin.znth.znVariant

app = FastAPI()

# 设置静态文件目录为Vue项目的构建输出目录（例如：dist）

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, Decimal):
            return float(o)
        return super().default(o)

app = FastAPI()


app.mount("/res", StaticFiles(directory="/devhhinfoDatas"), name="static")
app.mount("/equts", StaticFiles(directory="../web/equts/dist", html=True), name="equts")
app.mount("/admin", StaticFiles(directory="/project/znpower2025/web/admin/dist", html=True), name="admin")

@app.on_event("startup")
async def startup_event():
    app.json_encoder = DecimalEncoder


# 重定向根路径到index.html，确保Vue路由正常工作（单页应用）
@app.get("/equts", response_class=RedirectResponse)
async def redirect_to_index():
    return "/equts/index.html"

# 重定向根路径到index.html，确保Vue路由正常工作（单页应用）
@app.get("/admin", response_class=RedirectResponse)
async def redirect_to_index():
    return "/admin/index.html"


@app.post("/infoapi/{compCode}/{action}")
async def infoapi(request:Request, compCode: str , action:str , params:dict={}):
    res = {
        'status': 0,
        'result': None
    }
    try:
        client = request.client
        clientIp = client.host



        if compManager.checkClient(clientIp)<=0:
            return  res
        if  compCode not in compManager.components.keys():
            res['status'] = -1001
            res['result'] = "compCode error"
        else:
            comp = compManager.components[compCode]
            if action not in comp.handlers.keys():
                res['status'] = -1002
                res['result'] = "action  error"
            else:
                handler = comp.handlers[action]
                if action in comp.asyncHandlerKeys:
                    result = await  handler(**params)
                    res={
                        "status":1 ,
                        "result": result
                    }
                else:
                    res={
                        "status":1 ,
                        "result": handler(**params)
                    }
    except Exception as err:
        print(err)
    return res
@app.websocket('/wsinfoapi')
async def websocket_infoapiWs(websocket: WebSocket):
    try:
        client = websocket.client
        clientIp = client.host
        if   compManager.checkClient(clientIp)<=0:
            return

        if 'compWs' in compManager.components.keys():
            compWs = compManager.components['compWs']
            await compWs.acceptWs(websocket)
    except Exception as eer:
        print('yysportWs error.',eer)


if __name__ == "__main__":
    print ('command argvs:' , sys.argv)
    settingsCode ='default'
    for i in range(len(sys.argv)):
        if i<len(sys.argv)-1 and sys.argv[i] =='-s':
            settingsCode = sys.argv[i+1]
    print(f"settings code:{settingsCode}")
    compManager.loadComponents(settingsCode)

    host = compManager.settings['server']['host']
    port = compManager.settings['server']['port']
    checkClient = compManager.settings['server']['checkClient']
    uvicorn.run(app, host=host, port=port)